//
//  QueryAddressVC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/9/9.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "QueryAddressVC.h"
#import <Masonry.h>
#import "Common.h"
#import "area.h"
#import "QueryAddressCell.h"
#import "CustomTextField.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>


#define LeftTableTag  1000
#define RightTableTag  2000
#define SearchTableTag 3000
#define MySetValue(dict, value) ((!dict[value] || [dict[value] isKindOfClass:[NSNull class]])?@"":dict[value])

@interface QueryAddressVC ()<AMapSearchDelegate>
{
    UIImageView * nav;
    Common * com;
    NSMutableArray * dataSouceArr;
    UITableView * left_table;
    UITableView * right_table;
    UITableView * SearchTable;
    NSMutableArray * searchArr;

    NSMutableArray * cityListArr;
    NSMutableArray * pinyin;
    NSMutableDictionary * backAddressDic;
    area * AREA;
    NSInteger tableInteger;
    UIView * backview;

}
@property (nonatomic,strong) AMapSearchAPI * search;
@property (nonatomic,strong) AMapInputTipsSearchRequest *request;
@property (nonatomic, strong) NSMutableArray *provienceArray;
@property (nonatomic, strong) NSMutableArray *cityArray;
@property (nonatomic,strong) NSMutableArray * HotCityArr;
@property (nonatomic) int lenght;
@end

@implementation QueryAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    nav = [self createNav:@"选择城市"];
    [self.view addSubview:nav];
    self.view.backgroundColor = GrayColor;

    [self initTable];
    [self initData];
    
    _lenght = 0;
    
    
    [AMapServices sharedServices].apiKey =@"decee6229c378085197d527b8a20e32f";
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    self.request = [[AMapInputTipsSearchRequest alloc] init];
    
}

/*
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest*)request response:(AMapInputTipsSearchResponse *)response{
    
    if (response.tips.count == 0)
    {
        return;
    }else{
        
        [searchArr removeAllObjects];
        
        for (AMapTip *p in response.tips) {
            //把搜索结果存在数组
            
            //            NSLog(@"%@",p.address);
            NSLog(@"%@",p.name);
            
            [searchArr addObject:p];
        }
    }
    
    [SearchTable reloadData];
    
    //解析response获取POI信息，具体解析见 Demo
}
*/

-(void)initTable{
    
    UITextField * field = [self createField:@"按照城市名称/首字母/全拼音搜索" andFont:FontOfSize14];
    field.tag = 111111;
    [self.view addSubview:field];
    [field mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(18*kWidth);
        make.top.mas_equalTo(nav.mas_bottom).with.offset(18*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width-36*kWidth, 30*kHeight));
    }];

    left_table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64*kHeight, Main_Width, 86*kHeight) style:UITableViewStylePlain];
    [left_table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    left_table.tag = LeftTableTag;
    left_table.delegate = self;
    left_table.dataSource = self;
    [self.view addSubview:left_table];
    [left_table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.top.mas_equalTo(field.mas_bottom).with.offset(10*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width/2, Main_height-100*kHeight));
    }];
    right_table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64*kHeight, Main_Width, 86*kHeight) style:UITableViewStylePlain];
    [right_table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    right_table.tag = RightTableTag;
    right_table.backgroundColor = RGBACOLOR(240,241,242,1);
    right_table.delegate = self;
    right_table.dataSource = self;
    [self.view addSubview:right_table];
    [right_table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right);
        make.top.mas_equalTo(field.mas_bottom).with.offset(10*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width/2, Main_height-100*kHeight));
    }];
    
    backview = [[UIView alloc]init];
    backview.backgroundColor = WhiteColor;
    backview.hidden = YES;
    
    [self.view addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.mas_equalTo(field.mas_bottom).with.offset(8*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width, Main_height-field.frame.origin.y-field.frame.size.height));
    }];

    
    SearchTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64*kHeight, Main_Width, 86*kHeight) style:UITableViewStylePlain];
    [SearchTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    SearchTable.tag = SearchTableTag;
    SearchTable.delegate = self;
    SearchTable.dataSource = self;
    [backview addSubview:SearchTable];
    [SearchTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backview.mas_left);
        make.top.mas_equalTo(backview.mas_top);
        make.size.mas_equalTo(CGSizeMake(Main_Width,backview.frame.size.height-86*kHeight));
    }];
}

-(void)initData{
    
    tableInteger = 0;
    AREA = [[area alloc]init];
    dataSouceArr = [[NSMutableArray alloc]init];
    _HotCityArr = [[NSMutableArray alloc]init];
    com = [[Common alloc]init];
    _provienceArray = [[NSMutableArray alloc]init];
    backAddressDic = [[NSMutableDictionary alloc]init];
    
    [backAddressDic setObject:@"" forKey:@"provinceName"];
    [backAddressDic setObject:@"" forKey:@"provinceCode"];
    [backAddressDic setObject:@"" forKey:@"cityName"];
    [backAddressDic setObject:@"" forKey:@"cityCode"];
    [backAddressDic setObject:@"" forKey:@"countyName"];
    [backAddressDic setObject:@"" forKey:@"countyCode"];
    searchArr = [[NSMutableArray alloc]init];
    cityListArr = [[NSMutableArray alloc]init];
    
    [self initLeftDataSource];
    [left_table reloadData];
    [right_table reloadData];
    
}


-(void)initLeftDataSource
{
    
    NSString * url = [NSString stringWithFormat:@"%@",provinces_Url];
    [Common requestWithUrlString:url contentType:application_json finished:^(id responseObj) {
        
        _provienceArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];
        
        if (_provienceArray.count>0) {
            [left_table reloadData];
            [backAddressDic setObject:_provienceArray[0][@"provinceName"] forKey:@"provinceName"];
            [backAddressDic setObject:_provienceArray[0][@"provinceCode"] forKey:@"provinceCode"];
            [self initRightDataWith:_provienceArray[0][@"provinceCode"]];
        }
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

-(void)initRightDataWith:(NSString *)string
{
    NSString * url = [NSString stringWithFormat:@"%@?code=%@",counties_Url,string];
    
    [Common requestWithUrlString:url contentType:application_json finished:^(id responseObj) {

        _cityArray = responseObj[@"data"];
        [backAddressDic setObject:_cityArray[0][@"cityName"] forKey:@"cityName"];
        [backAddressDic setObject:_cityArray[0][@"cityCode"] forKey:@"cityCode"];

        if (_cityArray.count>0) {
            [right_table reloadData];
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *str=@"str";

    if (tableView.tag == LeftTableTag) {
        QueryAddressCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
        
        if (cell ==nil) {
            
            cell = [[QueryAddressCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
        
//        [left_table selectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
//        [self tableView:left_table didSelectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
//        
        NSDictionary *dict = [_provienceArray objectAtIndex:indexPath.row];
        cell.title.text = MySetValue(dict, @"provinceName");
        cell.title.textAlignment = NSTextAlignmentCenter;
        
        if (indexPath.row == tableInteger) {
            cell.title.textColor = YellowColor;
        }else{
            cell.title.textColor = BlackColor;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    }else if(tableView.tag == RightTableTag){
        
        QueryAddressCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
        
        if (cell ==nil) {
            
            cell = [[QueryAddressCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
        
        NSString *dict = [_cityArray objectAtIndex:indexPath.section][@"counties"][indexPath.row][@"countyName"];
        cell.title.text = dict;
        cell.backgroundColor = RGBACOLOR(240,241,242,1);
        return cell;
    }else{
        QueryAddressCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
        
        if (cell ==nil) {
            
            cell = [[QueryAddressCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }

        cell.title.text =[NSString stringWithFormat:@"%@",searchArr[indexPath.row][@"pName"]];
//        cell.title.text =[NSString stringWithFormat:@"%@",searchArr[indexPath.row]];
//        AMapTip * p = searchArr[indexPath.row];
//        cell.title.text = p.name;
        return cell;
    }
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    
    if (tableView == right_table) {
        return _cityArray.count;
    }else{
        return 1;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (tableView.tag == LeftTableTag) {
        return _provienceArray.count;
    }else if (tableView.tag == RightTableTag){
        return [_cityArray[section][@"counties"] count];
    }else{
        return  searchArr.count;
    }
}


-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (tableView == right_table) {
        UIView * view = [[UIView alloc]init];
        view.frame = CGRectMake(0, 0, Main_Width, 42*kHeight);
        view.backgroundColor = sectionHeadView;
        UILabel * label = [com createUIlabel:_cityArray[section][@"cityName"] andFont:FontOfSize14 andColor:BlackColor];
        [view addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(view.mas_centerX);
            make.centerY.equalTo(view.mas_centerY);
        }];
        return view;
  
    }else{
        return nil;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (tableView == right_table) {
        return 43*kHeight;
    }else{
        return 0.00001;
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 43*kHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (tableView.tag == LeftTableTag) {

        [backAddressDic setObject:_provienceArray[indexPath.row][@"provinceName"] forKey:@"provinceName"];
        [backAddressDic setObject:_provienceArray[indexPath.row][@"provinceCode"] forKey:@"provinceCode"];
        tableInteger = indexPath.row;
        [left_table reloadData];
        [self initRightDataWith:_provienceArray[indexPath.row][@"provinceCode"]];

        
    }else if(tableView.tag == RightTableTag){
        
        
        [backAddressDic setObject:_cityArray[indexPath.section][@"cityName"] forKey:@"cityName"];
        [backAddressDic setObject:_cityArray[indexPath.section][@"cityCode"] forKey:@"cityCode"];
        [backAddressDic setObject:_cityArray[indexPath.section][@"counties"][indexPath.row][@"countyName"] forKey:@"countyName"];
        [backAddressDic setObject:_cityArray[indexPath.section][@"counties"][indexPath.row][@"countyCode"] forKey:@"countyCode"];
                
        if (self.callAddressBack) {
            self.callAddressBack(backAddressDic,self.addresstype);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:searchArr[indexPath.row][@"cityCode"] forKey:@"cityCode"];
        [dic setObject:searchArr[indexPath.row][@"cityName"] forKey:@"cityName"];
        [dic setObject:searchArr[indexPath.row][@"countyCode"] forKey:@"countyCode"];
        [dic setObject:searchArr[indexPath.row][@"countyName"] forKey:@"countyName"];
        [dic setObject:searchArr[indexPath.row][@"provinceCode"] forKey:@"provinceCode"];
        [dic setObject:searchArr[indexPath.row][@"provinceName"] forKey:@"provinceName"];


        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.callAddressBack) {
                self.callAddressBack(dic,self.addresstype);
            }
            [self.navigationController popViewControllerAnimated:YES];
        });
        
        NSLog(@"search");
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)textFieldWithText1:(UITextField*)field{
    
    [SearchTable mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(backview.frame.size.height-300*kHeight);
    }];
    
}

-(void)textFieldWithText:(UITextField*)field{
    
    NSString * name1 = field.text;
    
    NSString *strUrl = [name1 stringByReplacingOccurrencesOfString:@" " withString:@""];

    if (field.text.length>0) {
   
        backview.hidden = NO;
//        self.request.keywords            = strUrl;
//        self.request.city                = @"北京";
//        [self.search AMapInputTipsSearch: self.request];
//        
        if (![strUrl isEqualToString:@"省"]&&![strUrl isEqualToString:@"市"]&&![strUrl isEqualToString:@"区"]&&![strUrl isEqualToString:@"县"]) {
           
            NSString * url = [NSString stringWithFormat:@"%@?params=%@",search_Url,strUrl];
            //url汉字转码
            NSString *str1 = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            [Common requestWithUrlString:str1 contentType:application_json finished:^(id responseObj) {
                
                NSArray * arr = responseObj[@"data"];
                if (arr.count>0) {
                    searchArr = [NSMutableArray arrayWithArray:responseObj[@"data"]];
                }else{
                    [searchArr removeAllObjects];
                }
                backview.hidden = NO;
                [SearchTable reloadData];
                
            } failed:^(NSString *errorMsg) {
                NSLog(@"%@",errorMsg);
            }];
        }
    }
    else{
        
        UITextField * field = (UITextField*)[self.view viewWithTag:111111];
        [field resignFirstResponder];
        
        [searchArr removeAllObjects];
        backview.hidden = YES;
        
        [SearchTable reloadData];

        
    }
    
}




//点击return按钮 键盘隐藏 这是协议中的方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [SearchTable mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(backview.frame.size.height-86*kHeight);
    }];
    
    //键盘隐藏 也就是让键盘取消第一响应者身份
    [textField resignFirstResponder];
    return YES;
}




-(UITextField*)createField:(NSString*)placeholder andFont:(double)font{
    
    UITextField * field =[[UITextField alloc]init];
    field.frame = CGRectMake(0, 0, Main_Width-91, 50);
    field.delegate = self;
    field.userInteractionEnabled = YES;
    field.textAlignment = NSTextAlignmentLeft;
    field.keyboardType = UIKeyboardTypeDefault;
    field.backgroundColor = WhiteColor;
    field.layer.cornerRadius = 5;
    field.layer.borderWidth = 0.5;
    field.layer.borderColor = WhiteColor.CGColor;

    UIImageView *accLeftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_search"]];
    accLeftView.frame = CGRectMake(20, 5, 24, 13);
    // 添加到左侧视图中
    field.leftView = accLeftView;
    field.leftViewMode = UITextFieldViewModeAlways; // 这句一定要加，否则不显示

    field.placeholder =placeholder;
    [field setFont:[UIFont fontWithName:@"STHeitiSC" size:font]];
    [field addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    [field addTarget:self action:@selector(textFieldWithText1:) forControlEvents:UIControlEventEditingDidBegin];

    [field placeholderRectForBounds:CGRectMake(100.0, 100.0, 100, 100)];

    return field;
}



@end
